let socketOpen = false
let socketMsgQueue = []
import {
	wsUrl
} from '@/config/config.js'
import {
	Stomp
} from './stomp.js'

export default {
	// ws地址
	wsUrl,
	// stomp实例
	client: null,
	// 重连间隔
	reconnectInterval: 5000,
	reconnectId: null,
	closeCallback: null, // 用于存储关闭事件的回调函数
	init() {
		if (this.client) {
			return Promise.resolve(this.client)
		}

		return new Promise((resolve, reject) => {
			const ws = {
				send: this.sendMessage,
				onopen: null,
				onmessage: null,
				close: this.closeSocket,
			}

			// uni.connectSocket({ url, header })
			uni.connectSocket({
				url: this.wsUrl
			})
			uni.onSocketOpen(function(res) {
				console.log('WebSocket连接已打开！', res)

				socketOpen = true
				for (let i = 0; i < socketMsgQueue.length; i++) {
					ws.send(socketMsgQueue[i])
				}
				socketMsgQueue = []

				ws.onopen && ws.onopen()
			})

			uni.onSocketMessage(function(res) {
				console.log("onSocketMessage", res)
				ws.onmessage && ws.onmessage(res)
			})

			uni.onSocketError(function(res) {
				console.log('WebSocket 错误！', res)
			})
			// 保存 closeCallback
			const self = this;
			uni.onSocketClose((res) => {
				this.client.disconnect()
				this.client = null
				socketOpen = false
				console.log('WebSocket 已关闭！', res)
				// 触发关闭事件的回调函数
				if (typeof self.closeCallback === 'function') {
					self.closeCallback(res);
				}
			})

			Stomp.setInterval = function(interval, f) {
				return setInterval(f, interval)
			}
			Stomp.clearInterval = function(id) {
				return clearInterval(id)
			}

			const client = (this.client = Stomp.over(ws))
			client.connect({}, function() {
				console.log('stomp connected')
				resolve(client)
			}, error => {
				// 重连
				this.reconnectId = setTimeout(() => {
					this.reconnect()
					console.log("重新连接")
				}, this.reconnectInterval)
			})
		})
	},
	reconnect() {
		// 连接
		console.log('重新连接')
		// this.init()
	},
	disconnect() {
		uni.closeSocket()
	},
	sendMessage(message) {
		if (socketOpen) {
			uni.sendSocketMessage({
				data: message,
			})
		} else {
			socketMsgQueue.push(message)
		}
	},
	closeSocket() {
		console.log('closeSocket')
	},
	// 设置关闭事件的回调函数
	setCloseCallback(callback) {
		this.closeCallback = callback;
	}
}